<template>
  <div class="test-results-container">
    <el-card class="test-results-card">
      <div slot="header">
        <span>我的测试结果</span>
      </div>

      <!-- 测试结果列表 -->
      <el-table
        v-loading="loading"
        :data="testResults"
        style="width: 100%">
        <el-table-column
          prop="testTime"
          label="测试时间"
          width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.testTime) }}
          </template>
        </el-table-column>

        <el-table-column
          prop="mbtiType"
          label="MBTI类型"
          width="120">
        </el-table-column>

        <!-- 各项得分列 -->
        <el-table-column label="各项得分" min-width="400">
          <template slot-scope="scope">
            <div class="score-container">
              <div class="score-row">
                <span class="score-label">外向(E):</span>
                <span class="score-value">{{ scope.row.eScore }}</span>
                <span class="score-label">内向(I):</span>
                <span class="score-value">{{ scope.row.iScore }}</span>
              </div>
              <div class="score-row">
                <span class="score-label">感觉(S):</span>
                <span class="score-value">{{ scope.row.sScore }}</span>
                <span class="score-label">直觉(N):</span>
                <span class="score-value">{{ scope.row.nScore }}</span>
              </div>
              <div class="score-row">
                <span class="score-label">思维(T):</span>
                <span class="score-value">{{ scope.row.tScore }}</span>
                <span class="score-label">情感(F):</span>
                <span class="score-value">{{ scope.row.fScore }}</span>
              </div>
              <div class="score-row">
                <span class="score-label">判断(J):</span>
                <span class="score-value">{{ scope.row.jScore }}</span>
                <span class="score-label">知觉(P):</span>
                <span class="score-value">{{ scope.row.pScore }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { testResultApi } from '@/api'

export default {
  name: 'StudentTestResults',
  data() {
    return {
      loading: false,
      testResults: [],
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  },
  created() {
    this.fetchTestResults()
  },
  methods: {
    formatDate(date) {
      if (!date) return '';
      try {
        return new Date(date).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        });
      } catch (error) {
        console.error('日期格式化错误:', error);
        return date;
      }
    },
    async fetchTestResults() {
      try {
        this.loading = true
        const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
        const res = await testResultApi.getByUserId(userInfo.userId)
        if (res.code === 200) {
          this.testResults = this.processTestResults(res.data)
          this.total = this.testResults.length
        } else {
          this.$message.error('获取测试结果失败')
        }
      } catch (error) {
        console.error('获取测试结果错误：', error)
        this.$message.error('获取测试结果失败')
      } finally {
        this.loading = false
      }
    },
    processTestResults(data) {
      if (!data || !Array.isArray(data)) return [];
      
      return data.map(item => this.processTestResult(item));
    },
    processTestResult(data) {
      if (!data) return null;
      
      // 创建结果对象
      const result = { ...data };
      
      // 处理时间字段 - 确保有testTime字段
      if (!result.testTime && result.test_time) {
        result.testTime = result.test_time;
      }
      
      // 分数字段映射（小写 -> 驼峰）
      const scoreFields = {
        'escore': 'eScore',
        'iscore': 'iScore',
        'sscore': 'sScore',
        'nscore': 'nScore',
        'tscore': 'tScore',
        'fscore': 'fScore',
        'jscore': 'jScore',
        'pscore': 'pScore'
      };
      
      // 将小写分数字段转换为驼峰命名字段
      for (const key in scoreFields) {
        if (data[key] !== undefined && data[key] !== null) {
          const camelCaseKey = scoreFields[key];
          result[camelCaseKey] = Number(data[key]);
        }
      }
      
      return result;
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchTestResults()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchTestResults()
    }
  }
}
</script>

<style scoped>
.test-results-container {
  padding: 20px;
}

.test-results-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 表格中的得分样式 */
.score-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.score-row {
  display: grid;
  grid-template-columns: auto auto auto auto;
  gap: 15px;
  align-items: center;
}

.score-label {
  font-size: 13px;
  color: #606266;
}

.score-value {
  font-size: 14px;
  color: #303133;
  font-weight: bold;
}
</style> 